package edu.pku.sei.mte.modification.command;

import edu.pku.sei.mte.exceptions.MultiValueBindingsException;
import edu.pku.sei.mte.mtemodel.model.MAttribute;
import edu.pku.sei.mte.mtemodel.mtmodel.expression.Expression;

public class UpdatingNodeCommand extends ModelModificationCommand {
	
	private MAttribute attribute;
	private Object oldValue;
	private Object newValue;

	public MAttribute getAttribute() {
		return attribute;
	}

	public void setAttribute(MAttribute attribute) {
		this.attribute = attribute;
	}

	public Object getOldValue() {
		return oldValue;
	}

	public void setOldValue(Object oldValue) {
		this.oldValue = oldValue;
	}

	public Object getNewValue() {
		return newValue;
	}

	public void setNewValue(Object newValue) {
		this.newValue = newValue;
	}

	@Override
	public void execute() throws Exception {
		if(getEnv().isAttributeBinded(attribute)){
			MultiValueBindingsException ex = new MultiValueBindingsException();
			ex.setContext(getContext());
			ex.setAttribute(attribute);
			ex.setOldValue(oldValue);
			ex.setNewValue(newValue);
			ex.setReturnValue(Expression.ERROR_VALUE);//default
			
			if(getEnv().getExhandler()!=null)
				getEnv().getExhandler().catchSemanticException(ex);
			newValue = attribute.getValue();
		}else {
			oldValue = attribute.getValue();
			attribute.setValue(newValue);
			getEnv().setAttributeBinded(attribute, newValue);
		}
		commit();
	}

	@Override
	public void undo() {
		newValue = attribute.getValue();
		attribute.setValue(oldValue);
	}
	
}
